package com.yan.club.sys.service.impl;

import com.yan.club.auth.model.AuthUser;
import com.yan.club.auth.model.LoginUser;
import com.yan.club.sys.mapper.SysUserMapper;
import com.yan.club.sys.model.SysUser;
import com.yan.club.sys.model.SysUserExample;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.yan.club.auth.utils.SecurityUtil.isAdmin;


/**
 * @author 彦
 * @since 2023/12/19 15:06
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

//    @Resource
//    private SysMapper sysMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查出用户信息
        SysUserExample userExample = new SysUserExample();
        userExample.createCriteria().andUserNameEqualTo(username);
        List<SysUser> users = sysUserMapper.selectByExample(userExample);

        if (users.isEmpty()) {
            throw new RuntimeException("用户不存在！");
        }

        // 查询对应权限信息
        Long userId = users.get(0).getUserId();
        List<String> list;
        if (isAdmin(userId)) {
            list = sysUserMapper.selectAllPerms();
        } else {
            list = sysUserMapper.selectPermsByUserId(userId);
        }
        AuthUser authUser = new AuthUser();
        BeanUtils.copyProperties(users.get(0), authUser);
        // 把数据封装成UserDetails返回
        return new LoginUser(authUser, list);
    }
}
